const path = require('path');
const low = require('lowdb');
const fs = require('fs');
const shortid = require('shortid');
const FileSync = require('lowdb/adapters/FileSync');
const Memory = require('lowdb/adapters/Memory');
const dbPath = path.join(__dirname, '../../_db_');

const formatDate = function () {
  const date = new Date();
  return `${date.getFullYear()}-${date.getMonth()}`;
};

function AppDb(dbName, fileName) {
  this.dbName = dbName;
  this.fileName = fileName;
}
AppDb.prototype.getFile = function (dbName, date) {
  return path.join(dbPath, `${dbName}.${date}.json`);
};

AppDb.prototype.getDb = function (fileName) {
  return low(
    process.env.NODE_ENV === 'development'
      ? new Memory()
      : new FileSync(fileName),
  );
};

AppDb.prototype.findDb = function (id, is) {
  if (this.fileName) {
    return this.getDb(path.join(dbPath, `${this.fileName}.json`));
  }
  const arr = id.split('!!');
  const fileName = this.getFile(this.dbName, arr[0]);
  if (!fs.existsSync(fileName)) {
    if (is) return this.getDb(fileName);
    return;
  }
  return this.getDb(fileName);
};
AppDb.prototype.findById = function (id) {
  const db = this.findDb(id);
  if (db) return db.get(id).toJSON();
};

AppDb.prototype.getId = function () {
  return formatDate() + '!!' + shortid.generate();
};
AppDb.prototype.get = function () {};

AppDb.prototype.add = async function (name) {
  const id = this.id();
  await this.db.set(this.id(), this.schema(name)).write();
  return id;
};

AppDb.prototype.saveById = async function (id, data) {
  const db = this.findDb(id, true);
  await db.set(id, this.schema(data)).write();
  return id;
};

module.exports = AppDb;
